using System;
using System.Windows;
using MySql.Data.MySqlClient;
using WpfApp1.Models;

namespace WpfApp1.DataAccess;

public class UserDataAccess : IUDataAccess
{
    public User? AuthenticateUser(string username, string password)
    {
        User? user = null;
        using (var connection = SqlAccess.CreateConnection())
        {
            try
            {
                connection.Open();
                var sql = "SELECT * FROM users WHERE username = @username AND password = @password";
                using (var command = new MySqlCommand(sql, connection))
                {
                    command.Parameters.AddWithValue("@username", username);
                    command.Parameters.AddWithValue("@password", password);
                    
                    using (var reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            user = new User(
                                reader.GetString("username"),    // varchar(50)
                                reader.GetString("password"),    // varchar(50)
                                reader.GetInt32("role"),         // int
                                reader.GetInt32("user_id")       // int
                            );
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"数据库连接错误: {ex.Message}");
                return null;
            }
        }
        return user;
    }
}